package cn.gengms.chat;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

import static cn.gengms.chat.ChatApplication.errorLogger;

@ServerEndpoint("/chat/{status}/{roomId}")
@Component
public class ChatSocketServer {

    public static Map<String, ArrayList<Session>> clients = new ConcurrentHashMap<>();
    public ObjectMapper objectMapper = new ObjectMapper();
    @OnOpen
    public void onOpen(Session session, @PathParam("status") Integer status, @PathParam("roomId") String roomId) throws InterruptedException, IOException {
       //创建房间
        if(status == 0){
           ArrayList<Session> sessions = new ArrayList<>();
           sessions.add(session);
           //String uuId = UUID.randomUUID().toString().substring(0,6);
           clients.put( roomId , sessions);
            System.out.println(clients);
       //加入房间
        }else if (status == 1){
           int size = clients.get(roomId).size();
           if(size >= 2){
               this.onClose(roomId, session);
           }else if(size == 1){
               clients.get(roomId).add(session);
           }else{
               this.onClose(roomId,session);
           }
            System.out.println(clients);
           if(clients.get(roomId).size() == 2){
               Message message = new Message();
               message.setType("hello");
               for(Session session1 : clients.get(roomId)){
                   session1.getAsyncRemote().sendText(objectMapper.writeValueAsString(message));
               }
               System.out.println("sure");
           }
       }else{
           this.onClose(roomId,session);
       }

    }
    @OnClose
    public void onClose(@PathParam("roomId") String roomId, Session session){
        if(clients.containsKey(roomId)){
            clients.get(roomId).remove(session);
        }
        if(clients.get(roomId).size() == 0){
            clients.remove(roomId);
        }
    }
    @OnError
    public void onError(Throwable throwable) {
        errorLogger.error("",throwable);
        throwable.printStackTrace();
    }
    @OnMessage
    public  void onMessage( @PathParam("roomId") String roomId, Session session,String message) throws IOException {
        System.out.println(message);
        int i = clients.get(roomId).indexOf(session);
        if(clients.get(roomId).size() == 1){

        }else{
            if(i == 1){
                i= 0;
            }else{
                i=1;
            }
            Session aim = clients.get(roomId).get(i);
            aim.getBasicRemote().sendText(message);
        }


    }
}
